﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Security;
using System.Web.Security;

namespace DotNet.Common
{
    /// <summary>
    /// 常用方法
    /// </summary>
    public class CommUtil
    {
        /// <summary>
        /// 获取一个小数的整数部分
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static int GetInt(int num)
        {
            string[] arr = num.ToString().Split('.');
            return int.Parse(arr[0]);
        }

        /// <summary>
        /// 过滤非法字符
        /// </summary>
        /// <param name="filterString"></param>
        /// <param name="exclueStr">排除的字符串，＂，＂分割如 ".,-,"</param>
        /// <returns></returns>
        public static string SafeFilter(string str,string exclueStr)
        {
            str = str.Replace(" ","");
            if (exclueStr.IndexOf("',") < 0)
            {
                str = str.Replace("'", "");
            }
            if (exclueStr.IndexOf(",,") < 0)
            {
                str = str.Replace(",", "");
            }
            if (exclueStr.IndexOf("-,") < 0)
            {
                str = str.Replace("-", "");
            }
            if (exclueStr.IndexOf("+,") < 0)
            {
                str = str.Replace("+", "");
            }
            if (exclueStr.IndexOf("%,") < 0)
            {
                str = str.Replace("%", "");
            }
            if (exclueStr.IndexOf("&,") < 0)
            {
                str = str.Replace("&", "");
            }
            if (exclueStr.IndexOf("$,") < 0)
            {
                str = str.Replace("$", "");
            }
            if (exclueStr.IndexOf("*,") < 0)
            {
                str = str.Replace("*", "");
            }
            if (exclueStr.IndexOf(".,") < 0)
            {
                str = str.Replace(".", "");
            }
            if (exclueStr.IndexOf("=,") < 0)
            {
                str = str.Replace("=", "");
            }
            if (exclueStr.IndexOf("(,") < 0)
            {
                str = str.Replace("(", "");
            }
            if (exclueStr.IndexOf("),") < 0)
            {
                str = str.Replace(")", "");
            }
            if (exclueStr.IndexOf("!,") < 0)
            {
                str = str.Replace("!", "");
            }
            if (exclueStr.IndexOf("@,") < 0)
            {
                str = str.Replace("@", "");
            }
            if (exclueStr.IndexOf("#,") < 0)
            {
                str = str.Replace("#", "");
            }
            if (exclueStr.IndexOf("^,") < 0)
            {
                str = str.Replace("^", "");
            }
            if (exclueStr.IndexOf("|,") < 0)
            {
                str = str.Replace("|", "");
            }
            if (exclueStr.IndexOf(":,") < 0)
            {
                str = str.Replace(":", "");
            }
            if (exclueStr.IndexOf("xp_cmdshell,") < 0)
            {
                str = str.Replace("xp_cmdshell", "");
            }
            if (exclueStr.IndexOf("/add,") < 0)
            {
                str = str.Replace("/add", "");
            }
            str = str.Replace("exec master.dbo.xp_cmdshell", "");
            str = str.Replace("net localgroup administrators", "");
            str = str.Replace("select", "");
            str = str.Replace("insert", "");
            str = str.Replace("delete from", "");
            str = str.Replace("drop table", "");
            str = str.Replace("update", "");
            str = str.Replace("truncate", "");
            str = str.Replace("from", "");
            return str;
        }

        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="NoHTML">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;
        }
        /// <summary>
        /// 过滤HTML中的不安全标签
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string RemoveUnsafeHtml(string content)
        {
            content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
            content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
            return content;
        }
        /// <summary>
        /// 检测是否有Sql危险字符
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeSqlString(string str)
        {

            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        /// <summary>
        /// 检测是否有危险的可能用于链接的字符串
        /// </summary>
        /// <param name="str">要判断字符串</param>
        /// <returns>判断结果</returns>
        public static bool IsSafeUserInfoString(string str)
        {
            return !Regex.IsMatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest");
        }

       /// <summary>
       /// 对md5改造的加密方法
       /// </summary>
       /// <param name="str"></param>
       /// <returns></returns>
        public static string DotEnCrypt(string str,int safeStart)
        {
            string strPre="",strEnd="";
            int startIndex = safeStart;
            str=FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            strEnd = DotReverse(str.Substring(startIndex, str.Length - startIndex));
            strPre = DotReverse(str.Substring(0, startIndex));
            return strEnd + strPre;
        }

        /// <summary>
        /// 字符串反转算法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string DotReverse(string str)
        {
            string ret = "";
            for (int i = str.Length-1; i > -1; i--)
            {
                ret += str.Substring(i, 1);
            }
            return ret;
        }

        public static void Debug(string str)
        {
            HttpContext.Current.Response.Write(str);
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 获取应用程序路径
        /// </summary>
        /// <param name="type">1 获取根目录，2　获取当前目录</param>
        /// <returns></returns>
        public static string GetAppPath(int type)
        {
            string retValue = "";
            if (type == 1)
            {
                retValue=HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"];
            }
            else
            {
                string str = HttpContext.Current.Request.ServerVariables["path_translated"];
                retValue = str.Substring(0,str.LastIndexOf("\\")+1);
            }
            return retValue;
        }

        /// <summary>
        /// 判断是否为数字类型的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumStr(string str)
        {
            bool b = true;
            foreach (char c in str)
            {
                if (!Char.IsNumber(c))
                {
                    b = false;
                    break;
                }
            }
            return b;
        }

        /// <summary>
        /// 生成时间加随机数的文件名称
        /// </summary>
        /// <returns></returns>
        public static string GetDataTimeRandomFileName()
        {
            Random r = new Random(1000);
            return DateTime.Now.Date.Year.ToString() + DateTime.Now.Date.Month.ToString() + DateTime.Now.Date.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + r.Next().ToString();
        }

        /// <summary>
        /// 生成随机字符
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GenRndString(int len)
        {
            string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToLower();
            char[] charArray = str.ToCharArray();
            int number;
            char code;
            string rndCode = String.Empty;

            Random random = new Random();

            for (int i = 0; i < len; i++)
            {
                number = random.Next();

                code = charArray[number % 50];

                rndCode += code.ToString();
            }

            return rndCode;
        }
        /// <summary>
        /// 获取随机数
        /// </summary>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string GenRndNum(int len)
        {
            string str = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
            string[] strArray = str.Split(new char[]{','});
            int number;
            string s=string.Empty;
            string strCode = String.Empty;

            Random random = new Random();

            for (int i = 0; i < len; i++)
            {
                number = random.Next();

                s = strArray[number % 15];
                if (s == "0")
                    s = "2";
                strCode += s;
            }

            return strCode;
        }

        /// <summary>
        /// 判断参数是否为空，是否是数字类型字符
        /// </summary>
        /// <param name="ID"></param>
        public static void ValidID(string ID)
        {
            if (ID.Trim() == ""||!IsNumStr(ID))
                throw new Exception("参数传递错误!");
        }
        /// <summary>
        /// 得到两个时间之间的时间段
        /// </summary>
        /// <param name="unit"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public static int DateDiff(string unit, DateTime startDate, DateTime endDate)
        {
            int retValue = 0;
            int diffYear = endDate.Year - startDate.Year;
            int diffMonth = endDate.Month - startDate.Month;
            int diffDay = endDate.Day - startDate.Day;
            int diffHour = endDate.Hour - startDate.Hour;
            int diffMinute = endDate.Minute - startDate.Minute;
            int diffSecond = endDate.Second - startDate.Second;
            if (unit == "year")
            {
                retValue = diffYear;
            }
            if (unit == "month")
            {
                retValue = diffYear * 12 + diffMonth;
            }
            if (unit == "day")
            {
                retValue = (diffYear * 12 + diffMonth)*30 + diffDay;
            }
            if (unit == "hour")
            {
                retValue = ((diffYear * 12 + diffMonth) * 30 + diffDay) * 24 + diffHour;
            }
            if (unit == "minute")
            {
                retValue = (((diffYear * 12 + diffMonth) * 30 + diffDay) * 24 + diffHour) * 60+diffMinute;
            }
            if (unit == "second")
            {
                retValue = ((((diffYear * 12 + diffMonth) * 30 + diffDay) * 24 + diffHour) * 60 + diffMinute) * 60;
            }
            return retValue;
        }
        /// <summary>
        /// 得到客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string lastIP = "";
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                lastIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                lastIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }

            return lastIP;
        }

        /// <summary>
        /// 按指定长度截取字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetSpeStr(string str, int slen,bool showDot)
        {
            if (str.Length > slen)
            {
                if(showDot)
                    str = str.Substring(0, slen) + "...";
                else
                    str = str.Substring(0, slen);
            }
            return str;
        }
        /// <summary>
        /// 过滤非法js字符
        /// </summary>
        /// <param name="str"></param>
        /// <param name="exclueStr"></param>
        /// <returns></returns>
        public static string JsFilter(string str, string exclueStr)
        {
            if (exclueStr.IndexOf("<script>,") <0)
            {
                str = str.Replace("<script>", "");
            }
            if (exclueStr.IndexOf("</script>,") < 0)
            {
                str = str.Replace("</script>", "");
            }
            if (exclueStr.IndexOf("javascript,") < 0)
            {
                str = str.Replace("javascript", "");
            }
            if (exclueStr.IndexOf("/,") < 0)
            {
                str = str.Replace("/", "");
            }
            if (exclueStr.IndexOf("',") < 0)
            {
                str = str.Replace("'", "");
            }
            if (exclueStr.IndexOf(";,") < 0)
            {
                str = str.Replace(";", "");
            }
            if (exclueStr.IndexOf("&,") < 0)
            {
                str = str.Replace("&", "");
            }
            if (exclueStr.IndexOf("#,") < 0)
            {
                str = str.Replace("#", "");
            }
            return str;
        }


    }
}
